import { Injectable, UnauthorizedException } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import configuration from '@/config/configuration';
import { ValidationTokenException } from '@/common/exceptions/custom-exception';
import { Types } from 'mongoose';

@Injectable()
export class AuthService {
  constructor(private jwtService: JwtService) {}

  async signIn(
    _id: string | Types.ObjectId,
    id: string,
    username: string,
    role: string,
  ): Promise<{ access_token: string }> {
    if (!username) {
      throw new UnauthorizedException();
    }
    const payload = { _id, id, username, role };
    return {
      access_token: await this.jwtService.signAsync(payload, {
        secret: configuration().jwt.secret,
      }),
    };
  }

  async verifyToken(token: string): Promise<any> {
    try {
      return await this.jwtService.verifyAsync(token, {
        secret: configuration().jwt.secret,
      });
    } catch (error) {
      throw new ValidationTokenException();
    }
  }

  decodeToken(authHeader: string): Promise<any> {
    const token = authHeader?.replace('Bearer ', '');
    try {
      const payload = this.jwtService.decode(token); // 会校验签名和过期时间
      return payload; // payload 通常包括 userId、username 等
    } catch (error) {
      throw new Error('Token 无效或已过期');
    }
  }
}
